<template>
  <div :class="{ hasTagsView: needTagsView }" class="main-content">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <a-card hoverable>
          <a-flex gap="small" justify="space-between">
            <a-form ref="queryFormRef" layout="inline" :model="queryParams">
              <a-form-item label="题库名称" name="repoName">
                <a-input v-model:value="queryParams.repoName" allow-clear placeholder="请输入题库名称"
                         @blur="handleQuery" @keyup.enter="handleQuery" />
              </a-form-item>
              <a-form-item label="标签名称" name="tagName">
                <a-select
                  v-model:value="queryParams.tag" mode="multiple"
                  allow-clear placeholder="选择标签" :virtual="false"
                  :options="repoTagList" :field-names="{label: 'tagName', value: 'tagId'}"
                  show-search optionFilterProp="tagName"
                  @change="handleQuery" @keyup.enter="handleQuery"
                />
              </a-form-item>
            </a-form>
            <a-flex justify="end">
              <el-button icon="Search" :loading="loading" round plain type="primary"
                         @click="handleQuery">搜索
              </el-button>
              <el-button icon="RefreshRight" :loading="loading" round
                         @click="resetQuery">重置
              </el-button>
            </a-flex>
          </a-flex>
        </a-card>
      </div>
    </transition>

    <a-card ref="cardRef" class="card-content" hoverable>
      <template #title>
        <el-row ref="headerRef" :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:repo:add']" round icon="Plus" plain type="primary" @click="handleAdd">
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:repo:edit']" round icon="Edit" plain type="success"
                       :disabled="selection.selectedKeys.value.length !== 1"
                       @click="handleUpdate()">修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:repo:remove']" round plain icon="Delete" type="danger"
                       :disabled="selection.selectedKeys.value.length === 0"
                       @click="handleBatchDelete()">删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['exam:repo:export']" round icon="Download" plain type="warning"
                       @click="handleExport">导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @resetQuery="resetQuery"
                         :columns="columns"/>
        </el-row>
      </template>
      <el-auto-resizer>
        <template #default="{height, width}">
          <a-spin :spinning="loading" size="large">
            <el-table-v2 :columns="columns" :data="repoList" row-key="repoId"
                         :height="tableHeight" :width="width" fixed>
              <template #header-cell="{ column }">
                <template v-if="column.dataKey === 'selection'">
                  <el-checkbox
                    :model-value="selection.isAllSelected.value"
                    :indeterminate="selection.isIndeterminate.value"
                    @change="selection.toggleAll"
                  />
                </template>
              </template>
              <template #cell="{column,rowData,rowIndex}">
                <template v-if="column.dataKey==='selection'">
                  <el-checkbox
                    :model-value="selection.selectedKeys.value.some(k=>k=== rowData.repoId)"
                    @change="selection.toggleSelection(rowData.repoId)"
                  />
                </template>
                <template v-if="column.dataKey === 'index'">
                  {{ rowIndex + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
                </template>
                <template v-if="column.dataKey === 'repoName'">
                  <el-link :underline="false" @click="handleView(rowData)">{{ rowData.repoName }}</el-link>
                </template>
                <template v-if="column.dataKey === 'tag'">
                  <a-flex gap="small" justify="center" wrap="wrap">
                    <a-tag v-for="(item,index) in rowData.tag" :color="getAntTagColor(index)" :key="item">{{ item }}
                    </a-tag>
                  </a-flex>
                </template>
                <template v-if="column.key==='questionTypeCount'">
                  <a-flex gap="small">
                    <el-tag v-for="(tag, index) in rowData.templateCount.questionTypeCount.slice(0, 3)"
                            :key="'type-'+index" type="info">
                      {{ QUESTION_TYPE_CONFIG[tag.questionType].label }} : {{ tag.count || 0 }}
                    </el-tag>
                    <el-tooltip v-if="rowData.templateCount.questionTypeCount.length>3">
                      <template #content>
                        <a-flex gap="small">
                          <el-tag v-for="tag in rowData.templateCount.questionTypeCount.slice(3)"
                                  :key="tag.questionType"
                                  type="info">
                            {{ QUESTION_TYPE_CONFIG[tag.questionType].label }} : {{ tag.count || 0 }}
                          </el-tag>
                        </a-flex>
                      </template>
                      <el-tag v-if="rowData.templateCount.questionTypeCount.length>3" type="info">...</el-tag>
                    </el-tooltip>
                  </a-flex>
                </template>


                <template v-if="column.dataKey === 'action'">
                  <el-tooltip content="题目管理" placement="top">
                    <el-button v-hasPermi="['exam:repo:query']" circle icon="Suitcase" plain type="success"
                               @click="handleDetail(rowData)"></el-button>
                  </el-tooltip>
                  <el-tooltip content="模板导入" placement="top">
                    <el-button v-hasPermi="['exam:repo:import']" circle icon="Upload" plain type="warning"
                               @click="handleImport(rowData)"></el-button>
                  </el-tooltip>
                  <!-- 表格操作列模板 -->
                  <a-dropdown>
                    <el-button circle icon="MoreFilled"></el-button>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item
                          key="edit" @click="handleUpdate(rowData)">
                          <svg-icon icon-class="edit" />
                          编辑
                        </a-menu-item>
                        <a-menu-item
                          key="delete" @click="handleDelete(rowData)">
                          <svg-icon icon-class="delete" />
                          删除
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </template>
              </template>
            </el-table-v2>
          </a-spin>
        </template>
      </el-auto-resizer>
    </a-card>
    <a-card hoverable ref="paginationRef" v-show="total>0">
      <pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum"
                  :total="total" @pagination="getList" />
    </a-card>
    <!--题库展示抽屉-->
    <!--    <el-drawer v-model="drawer.visible" :title="drawer.title" size="100%" class="full-drawer">-->
    <!--      <question-data :repoId="repoId" :drawerVisible="drawer.visible"></question-data>-->
    <!--    </el-drawer>-->
    <!-- 添加或修改题库对话框 -->
    <el-drawer v-model="dialog.visible" :title="dialog.title" append-to-body size="30%">
      <el-form ref="repoFormRef" :model="form" :rules="rules" label-width="25%">
        <el-form-item label="题库名称" prop="repoName">
          <el-input v-model="form.repoName" placeholder="请输入题库名称" />
        </el-form-item>
        <el-form-item label="是否共享" prop="shareFlag">
          <el-switch v-model="form.shareFlag" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="标签" prop="tagsNames">
          <el-select
            v-model="form.tag"
            :max-collapse-tags="3"
            :reserve-keyword="false"
            allow-create
            clearable
            collapse-tags
            collapse-tags-tooltip
            filterable
            multiple
            placeholder="选择标签"
            value-key="tagsName"
          >
            <el-option v-for="item in repoTagList" :key="item.tagId" :label="item.tagName"
                       :value="item.tagName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题库备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 试题导入对话框 -->
    <file-import :import-dialog="importDialog" :repo-id="currentRepoId" @update:visible="handleDialogClose" />
  </div>
</template>

<script lang="ts" name="Repo" setup>
import { addRepo, delRepo, getRepo, pageRepo, updateRepo } from '@/api/exam/repo';
import { RepoForm, RepoQuery, RepoVO } from '@/api/exam/repo/types';
import { TagTypeEnum, TagVO } from '@/api/exam/tag/types';
import useSettingsStore from '@/store/modules/settings';
import { getAntTagColor } from '@/utils/tagColor';
import { columns } from './data';

/*计算表格高度*/
import { useElTableHeight } from '@/utils/useElTableHeight';
import { listTag } from '@/api/exam/tag';
import router from '@/router';
import FileImport from '@/views/exam/repo/fileImport.vue';
import { QUESTION_TYPE_CONFIG } from '@/views/exam/template/info/config';
import { useSelection } from '@/utils/useSelection';

const cardRef = ref<HTMLElement | null>(null);
const headerRef = ref<any>(0);
const paginationRef = ref<any>(null);
const { tableHeight } = useElTableHeight(cardRef, [headerRef, paginationRef]);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const settingsStore = useSettingsStore();
const needTagsView = computed(() => settingsStore.tagsView);
const repoList = ref<RepoVO[]>([]);
const repoId = ref<string>('');
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
/*表格样式*/
const tableStyle = ref('Grid');

const queryFormRef = ref<ElFormInstance>();
const repoFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const importDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const handleDialogClose = (value) => {
  importDialog.visible = value;
  importDialog.title = '';
};
const drawer = reactive<DrawerOption>({
  visible: false,
  title: ''
});
const initFormData: RepoForm = {
  repoId: undefined,
  repoName: undefined,
  image: undefined,
  imageUrl: undefined,
  shareFlag: undefined,
  templateCount: undefined,
  tag: [],
  remark: undefined
};
const data = reactive<PageData<RepoForm, RepoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    repoName: undefined,
    tag: [],
    shareFlag: undefined,
    params: {}
  },
  rules: {
    repoName: [
      { required: true, message: '题库名称不能为空', trigger: 'blur' }
    ]
  }
});


const { queryParams, form, rules } = toRefs(data);

/** 查询题库列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageRepo(queryParams.value);
  repoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 使用多选逻辑
const selection = useSelection(
  repoList, 'repoId' // 指定唯一键字段
);

const repoTagList = ref<TagVO[]>([]);
/*查询题库标签列表 */
const getTemplateTagList = async () => {
  const res = await listTag({ tagType: TagTypeEnum.RepoType });
  repoTagList.value = res.data;
};


const handleDetail = (row: RepoVO) => {
  router.push('/exam/repo/detail/' + row.repoId);
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  repoFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.tag = [];
  handleQuery();
};

/*详细按钮操作*/
const handleView = (row: RepoVO) => {
  repoId.value = '';
  drawer.visible = true;
  drawer.title = '题目管理';
  repoId.value = row.repoId;
};

/*导入按钮操作*/
const currentRepoId = ref();
const handleImport = (row: RepoVO) => {
  currentRepoId.value = row.repoId;
  importDialog.visible = true;
  importDialog.title = '通过模板导入';
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加题库';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: RepoVO) => {
  reset();
  const _repoId = row?.repoId || selection.selectedKeys.value[0];
  const res = await getRepo(_repoId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改题库';
};

/** 提交按钮 */
const submitForm = () => {
  repoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.repoId) {
        await updateRepo(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addRepo(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.notifySuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleBatchDelete = async (row?: RepoVO) => {
  const _repoIds = row?.repoId || selection.selectedKeys.value;
  let length = row ? 1 : selection.selectedKeys.value.length;
  await proxy?.$modal.modal('删除数据', '确认删除这 ' + `<font color="red"> ${length}</font>` + ' 条数据吗？');
  await delRepo(_repoIds);
  proxy?.$modal.notifySuccess('删除成功');
  await getList();
};
const handleDelete = async (row?: RepoVO) => {
  const _repoIds = row?.repoId;
  const _repoName = row?.repoName;
  await proxy?.$modal.confirm(`确认删除题库 <strong>${_repoName}</strong> 吗?`).finally(() => loading.value = false);
  await delRepo(_repoIds);
  proxy?.$modal.notifySuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('exam/repo/export', {
    ...queryParams.value
  }, `repo_${new Date().getTime()}.xlsx`);
};

onMounted(() => {
  getTemplateTagList();
  getList();
});
</script>
<style lang="scss" scoped>

</style>
